#include "../include/i2c_driver.h"

bool writeI2C(int fd, unsigned char dev_addr, unsigned char reg_addr, unsigned char *reg_value,int count)
{
    int status = 0;
   	unsigned char bufs[10] = {reg_addr,0x0};
    struct i2c_rdwr_ioctl_data data;
    struct i2c_msg messages;
    
	memcpy(&bufs[1], reg_value, count);
    messages.addr = dev_addr;  //device address
    messages.flags = 0;       //write
    messages.len = count + 1;
    messages.buf = bufs;  

    data.msgs  = &messages;
    data.nmsgs = 1;
	status = ioctl(fd, I2C_RDWR, &data);

	usleep(5000);

	if (status < 0)
		return false;
    return true;
}

bool readI2C(int fd, unsigned char dev_addr, unsigned char reg_addr,unsigned char *val,int count)
{
    int ret;
    struct i2c_rdwr_ioctl_data data;
    struct i2c_msg messages[2];
   	unsigned char bufs[2] = {0,};

    messages[0].addr = dev_addr;  //device address
    messages[0].flags = 0;    //write
    messages[0].len = 1;
    messages[0].buf = &reg_addr;  //data address

    messages[1].addr = dev_addr;       //device address
    messages[1].flags = I2C_M_RD;  //read
    messages[1].len = count;
    //messages[1].buf = bufs;  
    messages[1].buf = val;  
    
    data.msgs  = messages;
    data.nmsgs = 2;
    if(ret = ioctl(fd, I2C_RDWR, &data) < 0){
        printf("read ioctl err\n");    
        return false;
    }
	usleep(5000);
    return true;
}

